package com.qzsoft.zhjd.server.modules.cement.service.impl;

import java.util.List;
import java.util.UUID;

import com.qzsoft.zhjd.server.modules.cement.service.CollectCementDataService;
import com.qzsoft.zhjd.server.modules.ludong.cement.entity.CementStabilizedMacadamCollectionEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.qzsoft.zhjd.server.common.utils.NumberUtils;
import com.qzsoft.zhjd.server.modules.cement.entity.CollectCementAlarmEntity;
import com.qzsoft.zhjd.server.modules.cement.entity.CollectCementDataEntity;
import com.qzsoft.zhjd.server.modules.cement.entity.CollectCementDataRatioEntity;
import com.qzsoft.zhjd.server.modules.cement.entity.CollectCementDataWeightEntity;
import com.qzsoft.zhjd.server.modules.cement.entity.CollectCementMatchEntity;
import com.qzsoft.zhjd.server.modules.cement.handler.CementAlarmHandler;
import com.qzsoft.zhjd.server.modules.cement.handler.CementCollectDataHandler;
import com.qzsoft.zhjd.server.modules.cement.handler.CementDataHandler;
import com.qzsoft.zhjd.server.modules.cement.handler.CementDataRatioHandler;
import com.qzsoft.zhjd.server.modules.cement.handler.CementDataWeightHandler;
import com.qzsoft.zhjd.server.modules.cement.mapper.CollectCementDataMapper;
import com.qzsoft.zhjd.server.modules.cement.model.CementCollectDataModel;
import com.qzsoft.zhjd.server.modules.cement.service.CollectCementAlarmService;
import com.qzsoft.zhjd.server.modules.cement.service.CollectCementDataRatioService;
import com.qzsoft.zhjd.server.modules.cement.service.CollectCementDataWeightService;
import com.qzsoft.zhjd.server.modules.cement.service.CollectCementMatchService;

/**
 * @ClassName CementDataServiceImpl
 * @Description 水稳数据业务接口实现
 * @author linhuawei
 * @since 2022-01-18
 */
@Service
public class CollectCementDataServiceImpl extends ServiceImpl<CollectCementDataMapper, CollectCementDataEntity>
        implements CollectCementDataService {

    @Autowired
    private CollectCementDataRatioService collectCementDataRatioService;

    @Autowired
    private CollectCementDataWeightService collectCementDataWeightService;

    @Autowired
    private CollectCementAlarmService collectCementAlarmService;

    @Autowired
    private CollectCementMatchService collectCementMatchService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(CementStabilizedMacadamCollectionEntity njData) {
        // 拌合站主键
        String stationCode = njData.getEquipmentNumber();
        if ("QLJTSW01".equals(stationCode)) {
            stationCode = "JD01CSB1";
        }

        // 数据转化
        CementCollectDataModel originalData = new CementCollectDataModel();
        originalData.setId(njData.getId());
        originalData.setMatchCode(njData.getProportionIdGet());
        originalData.setDischargeTime(njData.getDischargingTime());
        originalData.setSendTime(njData.getUploadTime());
        originalData.setStationCode(stationCode);
        originalData.setGravel1Act(NumberUtils.strToBigDecimal(njData.getMaterialYield1(), null));
        originalData.setGravel2Act(NumberUtils.strToBigDecimal(njData.getMaterialYield2(), null));
        originalData.setGravel3Act(NumberUtils.strToBigDecimal(njData.getMaterialYield3(), null));
        originalData.setGravel4Act(NumberUtils.strToBigDecimal(njData.getMaterialYield4(), null));
        originalData.setGravel5Act(NumberUtils.strToBigDecimal(njData.getMaterialYield5(), null));
        originalData.setGravel6Act(NumberUtils.strToBigDecimal(njData.getMaterialYield6(), null));
        originalData.setPowder1Act(NumberUtils.strToBigDecimal(njData.getMaterialYield7(), null));
        originalData.setPowder2Act(NumberUtils.strToBigDecimal(njData.getMaterialYield8(), null));
        originalData.setWaterAct(NumberUtils.strToBigDecimal(njData.getMaterialYield9(), null));
        originalData.setGravel1Theo(NumberUtils.strToBigDecimal(njData.getMaterialGiven1(), null));
        originalData.setGravel2Theo(NumberUtils.strToBigDecimal(njData.getMaterialGiven2(), null));
        originalData.setGravel3Theo(NumberUtils.strToBigDecimal(njData.getMaterialGiven3(), null));
        originalData.setGravel4Theo(NumberUtils.strToBigDecimal(njData.getMaterialGiven4(), null));
        originalData.setGravel5Theo(NumberUtils.strToBigDecimal(njData.getMaterialGiven5(), null));
        originalData.setGravel6Theo(NumberUtils.strToBigDecimal(njData.getMaterialGiven6(), null));
        originalData.setPowder1Theo(NumberUtils.strToBigDecimal(njData.getMaterialGiven7(), null));
        originalData.setPowder2Theo(NumberUtils.strToBigDecimal(njData.getMaterialGiven8(), null));
        originalData.setWaterTheo(NumberUtils.strToBigDecimal(njData.getMaterialGiven9(), null));

        // 删除已经存在的数据（防止因为各种原因数据重传造成的数据重复）
        String originalId = originalData.getId();
        deleteByOriginalId(stationCode, originalId);

        // 获取生产配比
        String matchCode = originalData.getMatchCode();
        CollectCementMatchEntity match = collectCementMatchService.getByStationCodeAndMatchCode(stationCode, matchCode);

        // 获取主键
        String id = UUID.randomUUID().toString().replace("-", "");

        // 重量信息
        CollectCementDataWeightEntity dataWeight = CementDataWeightHandler.coverTo(originalData, match);
        dataWeight.setId(id);

        // 处理占比信息
        CollectCementDataRatioEntity dataRatio = CementDataRatioHandler.coverTo(originalData, dataWeight.getBatchWeight(),
                match);
        dataRatio.setId(id);

        // 预警信息
        CollectCementAlarmEntity alarmEntity = CementAlarmHandler.coverTo(dataRatio);
        alarmEntity.setId(id);

        // 生产数主表
        CollectCementDataEntity data = CementDataHandler.coverTo(originalData, match, dataWeight);
        data.setId(id);
        data.setOriginalId(originalId);

        // 保存数据
        baseMapper.insert(data);
        collectCementDataRatioService.save(dataRatio);
        collectCementDataWeightService.save(dataWeight);
        collectCementAlarmService.save(alarmEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(CementCollectDataModel originalData) {
        // 删除已经存在的数据（防止因为各种原因数据重传造成的数据重复）
        String originalId = originalData.getId();
        String stationCode = originalData.getStationCode();
        deleteByOriginalId(stationCode, originalId);

        // 获取生产配比
        String matchCode = originalData.getMatchCode();
        CollectCementMatchEntity match = collectCementMatchService.getByStationCodeAndMatchCode(stationCode, matchCode);

        // 处理采集到的数据
        CementCollectDataHandler.handler(originalData, null == match);

        // 获取主键
        String id = UUID.randomUUID().toString().replace("-", "");

        // 重量信息
        CollectCementDataWeightEntity dataWeight = CementDataWeightHandler.coverTo(originalData, match);
        dataWeight.setId(id);

        // 处理占比信息
        CollectCementDataRatioEntity dataRatio = CementDataRatioHandler.coverTo(originalData, dataWeight.getBatchWeight(),
                match);
        dataRatio.setId(id);

        // 预警信息
        CollectCementAlarmEntity alarmEntity = CementAlarmHandler.coverTo(dataRatio);
        alarmEntity.setId(id);

        // 生产数主表
        CollectCementDataEntity data = CementDataHandler.coverTo(originalData, match, dataWeight);
        data.setId(id);

        // 保存数据
        baseMapper.insert(data);
        collectCementDataRatioService.save(dataRatio);
        collectCementDataWeightService.save(dataWeight);
        collectCementAlarmService.save(alarmEntity);
    }

    /**
     * @Title deleteByOriginalId
     * @Description 根据原始主键删除已经存在的数据
     * @param stationCode 拌合楼编号
     * @param originalId  原始主键
     */
    private void deleteByOriginalId(String stationCode, String originalId) {
        // 如果原始主键为空，不做处理
        if (ObjectUtils.isEmpty(originalId) || ObjectUtils.isEmpty(stationCode)) {
            return;
        }

        // 使用原始主键查询数据
        QueryWrapper<CollectCementDataEntity> queryWrapper = new QueryWrapper<CollectCementDataEntity>();
        queryWrapper.eq("station_code", stationCode);
        queryWrapper.eq("original_id", originalId);
        List<CollectCementDataEntity> list = baseMapper.selectList(queryWrapper);
        if (null == list || 0 == list.size()) {
            return;
        }

        // 删除已经存在的数据
        String id = list.get(0).getId();
        baseMapper.deleteById(id);
        collectCementDataRatioService.removeById(id);
        collectCementDataWeightService.removeById(id);
        collectCementAlarmService.removeById(id);
    }

}
